const _ = require("lodash");
const VueParser = require("vue-template-compiler");

module.exports = class VueTemplateToPug {
    deepTab = 0;

    text = "";

    tree = null;

    constructor(html) {
        this.ast = VueParser.compile(`
            <div>
                ${html}
            </div>
        `).ast;
        this.tree = _.cloneDeep(this.ast);
        this._walkAst(this.ast);
        this.text = this.text.replace(/\n *\n/g,'\n').replace(/\( +/g,"(")
    }

    static REGS = {
        classReg: /\s[:]*?class(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/
    }

    static isText(type) {
        return type === 2
    }

    static isEle(type) {
        return type === 1
    }

    static isExpression(type) {
        return type === 3
    }

    _createEleText(ele) {
        let blanks = this.deepTab === 0 ? "" : "\n";
        let eleClass = _.get(ele, 'staticClass', '').replace(/\"/g, "");
        let attrs = _.map(ele.attrsMap, (val, name) => {
            if (name === 'class') return '';

            if (!!val) {
                return ` ${name}="${val.replace(/"/g, "'")}"`
            } else {
                return ` ${name}`
            }
        }).join(" ");

        let attrsStr = !!attrs ? `(${attrs})` : '';
        let classAttrs = _.map(eleClass.split(" "), key => {
            if (!!key) {
                return "." + key
            }
        }).join("");

        for (let i = 0; i < this.deepTab; i++) {
            blanks += " "
        }
        return (blanks + ele.tag + classAttrs + attrsStr);
    }

    _createPug(child) {
        const {attrsList, type} = child;
        const {isEle, isExpression, isText} = VueTemplateToPug;

        if (isText(type)) {
            console.log(child.text)
            this.text += child.text.replace(/\n/g, "").replace(/^ */g, " ")
        }

        if (isEle(type)) {
            this.text += this._createEleText(child);
        }

        if (isExpression(type)) {
            this.text += child.text.replace(/\n/g, "").replace(/^ */g, " ")
        }


        this.deepTab += 1;
        this._walkAst(child);
        this.deepTab -= 1;
    }

    _walkAst(ast) {

        _.each(ast.scopedSlots, child => {
            this._createPug(child);
        })

        _.each(ast.children, child => {
            this._createPug(child);
        })


        if (_.get(ast, 'ifConditions', []).length > 0) {
            this.deepTab -= 1
            _.chain(ast.ifConditions).filter((condition)=>{
                return condition.exp !== ast.if
            }).each((item,itemIndex)=>{
                this._createPug(item.block)
            }).value()
            this.deepTab += 1
        }

        return this.text;
    }
}
